/**
 * Copyright (c) 2011-2014, junchen (homeanter@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package xin.tianhui.cloud.oss.service.aliyun.impl;

import java.net.URL;
import java.util.Date;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;

import lombok.extern.slf4j.Slf4j;
import xin.tianhui.cloud.oss.model.dto.FileDTO;
import xin.tianhui.cloud.oss.model.dto.UploadFileDTO;
import xin.tianhui.cloud.oss.service.OssService;

/**
 * @author junchen homeanter@163.com
 * @Data 2018-04-17 10:01:11
 */
@Slf4j
public class OssServiceImpl implements OssService{
	public FileDTO fileUpload(UploadFileDTO uploadFile) {
		try {
			// endpoint以杭州为例，其它region请按实际情况填写
			String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
			// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建
			String accessKeyId = "LTAIuYCGVv9ItXzo";
			String accessKeySecret = "umKQkxwcp1JzyZOhse06CXGqINmqk8";
			// 创建OSSClient实例
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			// 上传文件流
			ossClient.putObject("homeant",uploadFile.getName(), uploadFile.getStream());
			// 设置URL过期时间为1小时
			Date expiration = new Date(new Date().getTime() + 3600 * 1000);
			URL url = ossClient.generatePresignedUrl("homeant", uploadFile.getName(), expiration);
			log.debug("url:{}",url);
			FileDTO dto = new FileDTO();
			dto.setName(uploadFile.getName());
			dto.setUrl(url.toString());
			// 关闭client
			ossClient.shutdown();
			return dto;
		} catch (OSSException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return null;
	}
}
